package com.zxy.controlcenter.core.http;

import org.apache.commons.lang3.Validate;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

/**
 * 以静态变量保存Spring ApplicationContext, 可在任何代码任何地方任何时候取出ApplicaitonContext.
 *
 * @author zxy
 */
public class SpringContextHolder implements ApplicationContextAware, DisposableBean {

    private static ApplicationContext applicationContext = null;

    public SpringContextHolder() {
    }

    /**
     * 取得存储在静态变量中的ApplicationContext
     *
     * @return applicationContext
     */
    public static ApplicationContext getApplicationContext() {
        assertApplicationContext();
        return applicationContext;
    }

    /**
     * 从静态变量applicationContext中取得Bean, 自动转型为所赋值对象的类型.
     *
     * @param beanName 对象名称
     * @param <T>      对象类型
     * @return 对象
     */
    @SuppressWarnings("unchecked")
    public static <T> T getBean(String beanName) {
        assertApplicationContext();
        return (T) applicationContext.getBean(beanName);
    }

    /**
     * 从静态变量applicationContext中取得Bean, 自动转型为所赋值对象的类型.
     *
     * @param requiredType 对象类型
     * @param <T>          对象类型
     * @return 对象
     */
    public static <T> T getBean(Class<T> requiredType) {
        assertApplicationContext();
        return applicationContext.getBean(requiredType);
    }

    /**
     * 清除SpringContextHolder中的ApplicationContext为Null
     */
    public static void clearHolder() {
        applicationContext = null;
    }

    /**
     * 检查ApplicationContext不为空
     */
    private static void assertApplicationContext() {
        Validate.validState(applicationContext != null, "applicaitonContext属性未注入, 请在上下文中定义SpringContextHolder.");
    }

    /**
     * 实现ApplicationContextAware接口, 注入Context到静态变量中
     *
     * @param appContext 上下文对象
     * @throws BeansException bean异常
     */
    @Override
    public void setApplicationContext(ApplicationContext appContext) throws BeansException {
        applicationContext = appContext;
    }

    /**
     * 现DisposableBean接口, 在Context关闭时清理静态变量
     *
     * @throws Exception 异常
     */
    @Override
    public void destroy() throws Exception {
        SpringContextHolder.clearHolder();
    }
}
